﻿using System.Collections.Generic;
using System.Drawing;

namespace WindowsFormsApp1
{
    public class RayHeatMap
    {
        public float BrushStop { get; set; }
        public int Radius { get; set; }
        private struct HeatPoint
        {
            public Point point;
            public int value;
            public HeatPoint(Point point, int value)
            {
                this.point = point;
                this.value = value;
            }
        }
        private List<HeatPoint> _heatPoints = new List<HeatPoint>();


        public void AddPoint(Point point, int value)
        {
            _heatPoints.Add(new HeatPoint(point, value));
        }

        public void Draw(ref Bitmap bitmap)
        {
            Graphics surface = Graphics.FromImage(bitmap);

            foreach (HeatPoint heatPoint in _heatPoints)
                DrawHeatPoint(surface, heatPoint);

            surface.Dispose();
        }

        private System.Drawing.Drawing2D.ColorBlend GetColorBlend(int value)
        {
            System.Drawing.Drawing2D.ColorBlend colors = new System.Drawing.Drawing2D.ColorBlend(3);

            colors.Positions = new float[3] { 0, BrushStop, 1 };

            colors.Colors = new Color[3]
            {
                Color.FromArgb(0, Color.White),
                Color.FromArgb(value, Color.Black),
                Color.FromArgb(value, Color.Black)
            };
            return colors;
        }

        private void DrawHeatPoint(Graphics surface, HeatPoint heatPoint)
        {
            int x = heatPoint.point.X - Radius;
            int y = heatPoint.point.Y - Radius;
            int len = 2 * Radius;

            var ellipsePath = new System.Drawing.Drawing2D.GraphicsPath();
            ellipsePath.AddEllipse(x, y, len, len);

            System.Drawing.Drawing2D.PathGradientBrush brush = new System.Drawing.Drawing2D.PathGradientBrush(ellipsePath);
            System.Drawing.Drawing2D.ColorBlend gradientSpecifications = GetColorBlend(heatPoint.value);
            brush.InterpolationColors = gradientSpecifications;

            surface.FillEllipse(brush, x, y, len, len);
        }

        public void Colorize(ref Bitmap bitmap, string paletteFile)
        {
            int[] palette = LoadPalette(paletteFile);

            for (int y = 0; y < bitmap.Height; y++)
            {
                for (int x = 0; x < bitmap.Width; x++)
                    bitmap.SetPixel(x, y, Color.FromArgb(palette[(byte)~(((uint)(bitmap.GetPixel(x, y).ToArgb())) >> 24)]));
            }
        }

        private int[] LoadPalette(string paletteFile)
        {
            int[] palette = new int[256];
            Bitmap paletteImage = (Bitmap)Bitmap.FromFile(paletteFile);
            for (int i = 0; i < palette.Length - 1; i++)
            {
                palette[i] = paletteImage.GetPixel(i, 0).ToArgb();
            }
            palette[palette.Length - 1] = 0;
            return palette;
        }


    }
}
